package com.gzw.dms.activity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.gzw.dms.BuildConfig;
import com.gzw.dms.KJ.MyListView;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.adapter.OrderHistoryAdapter;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.bean.BackOrderInfo;
import com.gzw.dms.bean.OrderHistoryInfo;
import com.gzw.dms.bean.ShippingOrderInfo;
import com.gzw.dms.bean.SingnInfo;
import com.gzw.dms.bean.SpinnerInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.DateUtil;
import com.gzw.dms.utils.FileUtil;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.ToolFor9Ge;
import com.gzw.dms.utils.UrlUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StorageUtils;

public class BackOrderDetailActivity extends BaseActivity {
    private TextView tv_shiping_order_num, tv_custom_name, ic_time_limitation,
            tv_custom_tel, tv_receipt_name, tv_receipt_tel, tv_goods_name, tv_goods_weight,
            tv_goods_vol, tv_shipping_order_state,tv_end_mechanism,ic_remarks_order,ic_receipt_adress
            ,ic_staradress,ic_end_address,tv_send_mechanism,ic_remarks,ic_custom,ic_receipt;
    private EditText et_sign_remarks;
    private Button btn_edit;
    private Intent mIntent;
    private BackOrderInfo shippingOrder;
    private Context mContext;
    private Toolbar toolbar;
    //0、1为接单，2已接单，3电子围栏签收，4实际签收,5分配订单
    private  String state;
    private  String fpstste="0";
    private List<String> ls_map;
    private LinearLayout layout_receipt,layout_scan,layout_pazhao;
    private List<OrderHistoryInfo> orderHistoryInfos;
    private OrderHistoryAdapter orderAdapter;
    private MyListView lv_order;
    private LinearLayout layout_node;
    private TextView tv_look;
    private String path;
    private int REQUEST_CODE_CAMERA=1;
    private DatePickerDialog dpd;
    private int imgH = 800;
    private int imgW = 600;
    private ImageView iv_uploading;
    private String fileName1= "";
    private String newFileName;
    private String isUploadPhotos = "0";
    private  String fileRoot = "singReverseOrder";
    private ProgressDialog mProgressDialog;
    private SingnInfo info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initConfig();
        init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_back_order_detail);

    }

    @Override
    protected void initViews() {
        iv_uploading = ((ImageView) findViewById(R.id.iv_uploading));

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tv_shiping_order_num = (TextView) findViewById(R.id.ic_shiping_order_num).findViewById(R.id.tv_name);

        ic_staradress = (TextView) findViewById(R.id.ic_staradress).findViewById(R.id.tv_name);
        ic_end_address = (TextView) findViewById(R.id.ic_end_address).findViewById(R.id.tv_name);
        tv_send_mechanism = (TextView) findViewById(R.id.ic_send_mechanism).findViewById(R.id.tv_name);

        tv_custom_name = (TextView) findViewById(R.id.ic_custom_name).findViewById(R.id.tv_name);
        ic_custom = (TextView) findViewById(R.id.ic_custom).findViewById(R.id.tv_name);
        ic_time_limitation = (TextView) findViewById(R.id.ic_time_limitation).findViewById(R.id.tv_name);
        tv_custom_tel = (TextView) findViewById(R.id.ic_custom_tel).findViewById(R.id.tv_name);

        tv_receipt_name = (TextView) findViewById(R.id.ic_receipt_name).findViewById(R.id.tv_name);
        ic_receipt = (TextView) findViewById(R.id.ic_receipt).findViewById(R.id.tv_name);
        tv_receipt_tel = (TextView) findViewById(R.id.ic_receipt_tel).findViewById(R.id.tv_name);
        tv_end_mechanism = (TextView) findViewById(R.id.ic_end_mechanism).findViewById(R.id.tv_name);
        ic_receipt_adress = (TextView) findViewById(R.id.ic_receipt_adress).findViewById(R.id.tv_name);

        tv_goods_name = (TextView) findViewById(R.id.ic_goods).findViewById(R.id.tv_left);
        tv_shipping_order_state = (TextView) findViewById(R.id.ic_goods).findViewById(R.id.tv_right);
        tv_goods_weight = (TextView) findViewById(R.id.ic_goodsWV).findViewById(R.id.tv_left);
        tv_goods_vol = (TextView) findViewById(R.id.ic_goodsWV).findViewById(R.id.tv_right);

        ic_remarks = (TextView) findViewById(R.id.ic_remarks).findViewById(R.id.tv_name);
        ic_remarks_order = (TextView) findViewById(R.id.ic_remarks_order).findViewById(R.id.tv_name);

        et_sign_remarks = (EditText) findViewById(R.id.et_sign_remarks);

        btn_edit = (Button) findViewById(R.id.btn_edit);
        layout_node = (LinearLayout)findViewById(R.id.layout_node);
        layout_receipt = (LinearLayout)findViewById(R.id.layout_receipt);
        layout_scan = (LinearLayout)findViewById(R.id.layout_scan);
        layout_pazhao = (LinearLayout)findViewById(R.id.layout_pazhao);
//        layout_pazhao.setVisibility(View.GONE);
        lv_order = (MyListView)findViewById(R.id.list_node);
        tv_look= (TextView) findViewById(R.id.tv_look);

    ;}

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("运单详情");
        mIntent = getIntent();
        ls_map = new ArrayList<>();
        shippingOrder = (BackOrderInfo) mIntent.getExtras().get(
                "shippingOrder");
        fpstste=(String)mIntent.getExtras().get("fpstste");
        setData(shippingOrder);
        setSupportActionBar(toolbar);

    }

    @Override
    protected void initEvents() {
        btn_edit.setOnClickListener(new mOnClick());
        tv_look.setOnClickListener(new mOnClick());
        toolbar.setNavigationOnClickListener(new mOnClick());
        iv_uploading.setOnClickListener(new mOnClick());

    }

    private void setData(BackOrderInfo shippingOrderInfo) {
        tv_shiping_order_num.setText("货运编号:" + "    " + shippingOrderInfo.getShiping_order_num());
        ic_staradress.setText("起运位置:" + "    " + shippingOrderInfo.getSend_station());
        ic_end_address.setText("调拨/退货始发位置:" + "    " + shippingOrderInfo.getEnd_address());
        tv_send_mechanism.setText("受理机构:" + "    " + shippingOrderInfo.getSend_mechanism());

        tv_custom_name.setText("发货客户名称:" + "    " + shippingOrderInfo.getCustom_name());
        ic_custom.setText("发货联系人:" + "    " + shippingOrderInfo.getCustom_contact());
        ic_time_limitation.setText("提货时效:" + "    " + shippingOrderInfo.getTime_limitation());
        tv_custom_tel.setText("发货客户电话:" + "    " + shippingOrderInfo.getCustom_tel());

        tv_goods_name.setText("货物名称:" + "    " + shippingOrderInfo.getGoods_name());
        tv_goods_weight.setText("总重量:" + "    " + shippingOrderInfo.getGoods_weight());
        tv_goods_vol.setText("总体积:" + "    " + shippingOrderInfo.getGoods_vol());

        if (shippingOrderInfo.getOrder_type()==0){
            tv_shipping_order_state.setText("逆向物流类型:" + "    " +"退货");
            layout_receipt.setVisibility(View.GONE);
        }else {
            tv_shipping_order_state.setText("逆向物流类型:" + "    " +"调拨");
            layout_receipt.setVisibility(View.VISIBLE);
            tv_receipt_name.setText("收货客户名称:" + "    " + shippingOrderInfo.getReceipt_name());
            ic_receipt.setText("收货联系人:" + "    " + shippingOrderInfo.getReceipt_contact());
            tv_receipt_tel.setText("收货客户电话:" + "    " + shippingOrderInfo.getReceipt_tel());
            ic_receipt_adress.setText("收货客户地址:" + "    " + shippingOrderInfo.getReceipt_address());
            tv_end_mechanism.setText("调拨/退货终到位置:" + "    " + shippingOrderInfo.getEnd_mechanism());
        }
        tv_goods_weight.setText("总件数:" + "    " + shippingOrderInfo.getGoods_num() );
        tv_goods_vol.setText("实际件数:" + "    " + shippingOrderInfo.getReal_num());
        UserInfo userInfo = MyApplication.getUserInfo();
        String flag = userInfo.getFlag();
        if (flag.equals("3")||flag.equals("4")){
            ic_remarks_order.setText("项目部备注:" + "    " + shippingOrderInfo.getRemarks_order());
            ic_remarks.setVisibility(View.GONE);
        }else {
            ic_remarks.setText("供应商/司机备注:" + "    " + shippingOrderInfo.getRemarks());
            ic_remarks_order.setVisibility(View.GONE);

        }

        //订单状态
        state = String.valueOf(shippingOrderInfo.getShipping_order_state());
        if (fpstste.equals("7")){
            if(state.equals("2")){
                tv_shipping_order_state.setText("运单状态:    已提货");
                btn_edit.setVisibility(View.GONE);
                layout_scan.setVisibility(View.GONE);
                layout_node.setVisibility(View.VISIBLE);
                ReceiveOrderTask showOrderTask = new ReceiveOrderTask();
                showOrderTask.execute();
            }else if(state.equals("4")){
                tv_shipping_order_state.setText("运单状态:    已签收");
                btn_edit.setVisibility(View.GONE);
                layout_scan.setVisibility(View.GONE);
                layout_node.setVisibility(View.VISIBLE);
                ReceiveOrderTask showOrderTask = new ReceiveOrderTask();
                showOrderTask.execute();
            }else {
                btn_edit.setVisibility(View.GONE);
                layout_scan.setVisibility(View.GONE);
            }

        }else {
            if(state.equals("2")){
                tv_shipping_order_state.setText("运单状态:    已提货");
                btn_edit.setText("签    收");
                btn_edit.setVisibility(View.VISIBLE);
                layout_node.setVisibility(View.GONE);
                layout_scan.setVisibility(View.VISIBLE);
            }else if(state.equals("4")){
                tv_shipping_order_state.setText("运单状态:    已签收");
                btn_edit.setVisibility(View.GONE);
                layout_scan.setVisibility(View.GONE);
                layout_node.setVisibility(View.VISIBLE);
                ReceiveOrderTask showOrderTask = new ReceiveOrderTask();
                showOrderTask.execute();
            }else {
                btn_edit.setVisibility(View.GONE);
                layout_scan.setVisibility(View.GONE);
            }
        }


    }
    class mOnClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_edit:
                    SaveHttpClientPost();
                    break;
                case R.id.tv_look:
                    Intent mIntetn1 = new Intent();
                    Bundle bundle1 = new Bundle();
                    mIntetn1.setClass(mContext, WebViewActivity.class);
                    bundle1.putSerializable("shippingOrder", shippingOrder.getShiping_order_id());
                    bundle1.putString("state", "2");
                    mIntetn1.putExtras(bundle1);
                    startActivityForResult(mIntetn1, 1);
                    break;


                case R.id.iv_uploading:
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            path = resultList.get(0).getPhotoPath().toString();
                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .showImageOnFail(R.drawable.ic_gf_default_photo)
                                    .showImageForEmptyUri(R.drawable.ic_gf_default_photo)
                                    .showImageOnLoading(R.drawable.ic_gf_default_photo).build();
                            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file:/" + path, iv_uploading, options);

                            if (!isNull(path)) {
                                fileName1 = shippingOrder.getShiping_order_num().trim() + "--" + DateUtil.getFileName();
                                uploadPhotos(path, fileName1);

                            }
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            T.showShort(getApplicationContext(), errorMsg);
                            Log.e("onHanlderFailure", "");
                        }
                    });
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //普通签收
        if (resultCode == 1) {
            Intent mIntent = new Intent();
            //设置返回数据
            setResult(1, mIntent);
            finish();
        }
    }

    public class ReceiveOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(String... params) {
            Map<String, Object> map = new HashMap<>();
            map.put("order_id", shippingOrder.getShiping_order_id());
            map.put("type", "2");
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appGetOrderMessage"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else if (result.indexOf("successMsg") > 0){
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    orderHistoryInfos = JsonUtil.getPersons(successMsg, new TypeToken<List<OrderHistoryInfo>>() {
                    }.getType());
                    orderAdapter = new OrderHistoryAdapter(mContext, orderHistoryInfos);
                    lv_order.setAdapter(orderAdapter);
                }
            }
        }
    }

    public void SaveHttpClientPost() {

//        isUploadPhotos = FileUtil.getInstance().isUpload();
//        if (isUploadPhotos=="0") {
//            T.showShort(mContext, "请上传图片");
//            return;
//        }else if(isUploadPhotos=="1"){
//            T.showShort(mContext, "请等待图片上传");
//            return;
//        }

        if (info == null)
            info = new SingnInfo();
        info.setOrder_id(shippingOrder.getShiping_order_id());
        info.setSign_remarks(et_sign_remarks.getText().toString().trim());
        SignShipOrder signShipOrder = new SignShipOrder();
        signShipOrder.execute(info);
    }


    public class SignShipOrder extends AsyncTask<SingnInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);

        }

        protected String doInBackground(SingnInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("sign_order", params[0]);
            map.put("newFileName", fileName1);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appSignReverseOrder"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }

    private void uploadPhotos(String path, String fileName){

        Bitmap bitmap = null;
        File file = new File(path);
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                bitmap = BitmapFactory.decodeStream(fis);
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (bitmap!=null) {
//                newFileName = shippingOrder.getShiping_order_num()+"--"+DateUtil.getFileName();
                bitmap = ToolFor9Ge.zoomImg(bitmap, imgW, imgH);
                FileUtil.getInstance().uploadFile(bitmap, fileName,fileRoot);
            }
            if(bitmap.isRecycled()==false) //如果没有回收
                bitmap.recycle();
        }
    }

    private void initConfig() {
        //配置主题
        //ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder()

                .build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(false)
                .build();

        //配置imageloader
        ImageLoader imageloader = new UILImageLoader();
        //设置核心配置信息
        CoreConfig coreConfig = new CoreConfig.Builder(getApplicationContext(), imageloader, theme)
                .setDebug(BuildConfig.DEBUG)
                .setFunctionConfig(functionConfig)

                .build();
        GalleryFinal.init(coreConfig);
    }

    private void init() {
        File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3) // default
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
    }
}
